// Copyright 2022 The kubegems.io Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package route

type PathTokens struct {
	Tokens []string
}

func ParsePathTokens(path string) []string {
	tokens := []string{}
	pos := 0
	for i, char := range path {
		if char == '/' {
			if pos != i {
				tokens = append(tokens, path[pos:i])
			}
			tokens = append(tokens, "/")
			pos = i + 1
		}
	}
	if pos != len(path) {
		tokens = append(tokens, path[pos:])
	}
	return tokens
}

func CompilePathPattern(pattern string) ([][]Element, error) {
	sections := [][]Element{}
	pathtokens := ParsePathTokens(pattern)
	for _, token := range pathtokens {
		if token == "/" {
			sections = append(sections, []Element{{kind: ElementKindSplit}})
			continue
		}
		compiled, err := CompileSection(token)
		if err != nil {
			return nil, err
		}
		sections = append(sections, compiled)
	}
	return sections, nil
}
